package com.example.rbq.coord

import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.example.rbq.R
import com.google.android.material.appbar.AppBarLayout
import kotlin.math.abs


class BgBehavior @JvmOverloads constructor(context: Context,
                                           attrs: AttributeSet) : AppBarLayout.Behavior(context, attrs){

    override fun onLayoutChild(parent: CoordinatorLayout, abl: AppBarLayout, layoutDirection: Int): Boolean {

        val imgBg = abl.findViewById<ImageView>(R.id.img_bg)

        /**
         * 处于中心时候原始X轴
         */
        var mOriginalHeaderX = 0
        /**
         * 处于中心时候原始Y轴
         */
        var mOriginalHeaderY = 0

        abl.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            //计算imgBg从开始移动到最后的百分比
            val offset = abs(verticalOffset).toFloat()
            var percent = offset / (appBarLayout.totalScrollRange.toFloat() * 0.7f)
            //百分大于1，直接赋值为1
            if (percent >= 1) {
                percent = 1f
            }
            val alpha = 1 - percent
            //设置透明度
            imgBg.alpha = alpha

        })

        return super.onLayoutChild(parent, abl, layoutDirection)
    }
}